<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关联分类ID" prop="cateId">
        <el-input
          v-model="queryParams.cateId"
          placeholder="请输入关联分类ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="cateName">
        <el-input
            v-model="queryParams.cateName"
            placeholder="请输入分类名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间" prop="uploadTime">
        <el-date-picker clearable
          v-model="queryParams.uploadTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择上传时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:guide:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:guide:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:guide:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:guide:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="guideList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="指南ID" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="关联分类ID" align="center" prop="cateId" />
      <el-table-column label="分类名称" align="center" prop="cateName" />
      <el-table-column label="文章内容" align="center" prop="content" />
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column label="状态：1启用、0停用" align="center" prop="status" />
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:guide:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:guide:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改就诊指南对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="guideRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="关联分类" prop="cateId">
          <el-select v-model="form.cateId" placeholder="请输入关联分类ID" clearable style="width: 100%">
            <el-option
                v-for="cate in cateOptions"
                :key="cate.id"
                :label="`${cate.id} - ${cate.cateName}`"
                :value="cate.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="上传时间" prop="uploadTime">
          <el-date-picker clearable
            v-model="form.uploadTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择上传时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Guide">
import { listGuide, getGuide, delGuide, addGuide, updateGuide } from "@/api/system/guide"
import {getCate, listCate} from "@/api/system/cate";

const { proxy } = getCurrentInstance()

// 添加分类选项响应式变量
const cateOptions = ref([])

const guideList = ref([{
  title: null,
  cateId: null,
  content: null,
  author: null,
  status: null,
  uploadTime: null,
  cateName: null
}])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    cateId: null,
    content: null,
    author: null,
    status: null,
    uploadTime: null,
    cateName: null
  },
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    cateId: [
      { required: true, message: "关联分类ID不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "文章内容不能为空", trigger: "blur" }
    ],
    author: [
      {required: true,message: "作者不能为空", trigger: "blur"}
    ],
    uploadTime: [
      { required: true, message: "上传时间不能为空", trigger: "blur" }
    ],
    status: [],
    createTime: [],
    updateTime:[]
  }
})

const { queryParams, form, rules } = toRefs(data)
/** 查询就诊指南列表 */
function getList() {
  loading.value = true
  listGuide(queryParams.value).then(async response => {
    //先清空数组，再 push 新数据
    guideList.value = []
    //使用 Promise.all 并行获取分类名称，避免顺序错乱
    const rowsWithCateName = await Promise.all(
        response.rows.map(async (row) => {
          const cateName = (await getCate(row.cateId)).data.cateName
          return { ...row, cateName } // 返回新对象，避免污染原数据
        })
    )
    //使用 push 或直接赋值，确保数据完整
    guideList.value.push(...rowsWithCateName)
    total.value = response.total
    loading.value = false
  }).catch(error => {
    loading.value = false
    console.error("加载失败:", error)
  })
}

// 获取所有分类选项
function getAllCateOptions() {
  // 使用较大的pageSize获取所有分类
  listCate({ pageNum: 1, pageSize: 1000 }).then(response => {
    cateOptions.value = response.rows
    console.log(cateOptions)
  }).catch(error => {
    console.error("获取分类列表失败:", error)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    cateId: null,
    content: null,
    author: null,
    status: null,
    uploadTime: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("guideRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加就诊指南"
  // 打开对话框时获取分类选项
  getAllCateOptions()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  // 打开对话框时获取分类选项
  getAllCateOptions()
  getGuide(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改就诊指南"
  })
}

/** 提交按钮 */
async function submitForm() {
  // 验证关联分类ID是否存在
  const cateId = form.value.cateId
  if (cateId) {
    try {
      const response = await getCate(cateId)
      console.log(response)
      if (!response.data || !response.data.id) {
        proxy.$modal.msgError("没有此分类ID，请重新输入")
        return
      }
    } catch (error) {
      proxy.$modal.msgError("没有此分类ID，请重新输入")
      return
    }
  }
  proxy.$refs["guideRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateGuide(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGuide(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除就诊指南编号为"' + _ids + '"的数据项？').then(function() {
    return delGuide(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/guide/export', {
    ...queryParams.value
  }, `guide_${new Date().getTime()}.xlsx`)
}

// 在组件挂载时获取分类选项
onMounted(() => {
  getAllCateOptions()
})

onActivated(() => {
  // 当组件从缓存中重新激活时调用
  getList();
});
</script>
